<template>
  <div>
    <a-tabs
      v-model:activeKey="activePaneKey"
      hide-add
      type="editable-card"
      @edit="onPaneRemove"
    >
      <template #rightExtra>
        <a-dropdown :trigger="['click']">
          <a-button type="primary" size="small">
            <template #icon>
              <PlusOutlined />
            </template>
            条款
          </a-button>
          <TextTip tips="模板内同一类型条款只能添加一个" />
          <template #overlay>
            <a-menu>
              <a-menu-item
                v-for="clause of clauseList"
                :key="clause.id"
                @click="onPaneAdd(clause)"
              >
                {{ clause.name }}
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>

      <a-tab-pane
        v-for="clauseContent in dataList"
        :key="clauseContent.key"
        :tab="clauseContent.name"
        :closable="dataList.length > 1"
        :forceRender="true"
      >
        <PaneContent :content="clauseContent" />
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script>
import { computed, defineComponent, reactive, toRefs, watch } from "vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import request from "../../../../common/utils/request";
import { useRoute } from "vue-router";
import PaneContent from "./PaneContent.vue";
import store from "../../../../store";
import { message } from "ant-design-vue";
import { TextTip } from "bl-common-vue3";

export default defineComponent({
  name: "CTClauseContent",
  components: { PlusOutlined, PaneContent, TextTip },
  props: {
    validateTrigger: {
      type: Number,
      default: 0,
    },
  },
  setup(props, { emit }) {
    const route = useRoute();

    const state = reactive({
      id: route.query.id || 0,
      clauseList: [],
      activePaneKey: "",
      dataList: [],
    });

    /** 添加条款内容 */
    let paneCount = 0; // 自增值，用于标识pane key的唯一性
    const onPaneAdd = (clause, initAdd = false) => {
      if (!initAdd && clause.attribute != "other") {
        const index = state.dataList.findIndex(
          (item) => item.attribute == clause.attribute
        );
        if (index > -1) {
          message.warning("您已添加过该类型条款~");
          return;
        }
      }
      paneCount++;
      const clauseContent = {
        ...clause,
        key: `${clause.attribute}_${paneCount}`,
      };
      state.dataList.push(clauseContent);
      if (!initAdd) {
        // 手动添加条款时默认选中
        state.activePaneKey = clauseContent.key;
      }
    };

    /** 删除条款内容 */
    const onPaneRemove = (key) => {
      const index = state.dataList.findIndex((item) => item.key == key);
      if (state.activePaneKey == key) {
        state.activePaneKey =
          index - 1 > -1
            ? state.dataList[index - 1].key
            : state.dataList[0].key;
      }
      state.dataList.splice(index, 1);
    };

    /** 获取初始条款内容 */
    const getInitDataList = () => {
      state.dataList = [];
      const detail = store.getters.currentContractTpl;
      if (detail.multiple_clause) {
        for (let clause of detail.multiple_clause) {
          onPaneAdd(clause, true);
        }
      } else {
        for (let clause of state.clauseList) {
          if (clause.clause_type != 3) {
            // 非用户自定义条款（系统默认条款）
            onPaneAdd(clause, true);
          }
        }
      }
      state.activePaneKey = state.dataList[0].key;
    };

    /** 获取条款下拉列表 */
    const getClauseList = () => {
      request.get("/org", "/contract/clause").then((res) => {
        state.clauseList = res.list;
        getInitDataList();
      });
    };

    /** 提交 */
    const validateForm = () => {
      emit("getResult", {
        params: {
          multiple_clause: state.dataList,
        },
        type: "ClauseContent",
      });
    };
    watch(
      () => props.validateTrigger,
      () => {
        validateForm();
      }
    );

    /** 初始化 */
    const init = () => {
      getClauseList();
    };
    init();

    return {
      ...toRefs(state),
      onPaneRemove,
      onPaneAdd,
    };
  },
});
</script>
